#pragma once

#include <string>
#include <fstream>
#include <unordered_map>
#include <memory>

namespace MiniDB
{

    class FileHandle
    {
    public:
        explicit FileHandle(const std::string &filename);
        ~FileHandle();

        // 禁用拷贝
        FileHandle(const FileHandle &) = delete;
        FileHandle &operator=(const FileHandle &) = delete;

        // 允许移动
        FileHandle(FileHandle &&) noexcept;
        FileHandle &operator=(FileHandle &&) noexcept;

        // 文件操作
        bool readBlock(int block_id, char *buffer, size_t block_size);
        bool writeBlock(int block_id, const char *buffer, size_t block_size);
        bool appendBlock(const char *buffer, size_t block_size);
        int getBlockCount();
        size_t getFileSize();
        void flush();
        bool isOpen() const;

    private:
        std::string filename_;
        std::fstream file_;
        bool is_open_;
    };

    class FileManager
    {
    public:
        static FileManager &getInstance();

        // 禁用拷贝和移动
        FileManager(const FileManager &) = delete;
        FileManager &operator=(const FileManager &) = delete;
        FileManager(FileManager &&) = delete;
        FileManager &operator=(FileManager &&) = delete;

        // 文件管理
        std::shared_ptr<FileHandle> createFile(const std::string &filename);
        std::shared_ptr<FileHandle> openFile(const std::string &filename);
        void closeFile(const std::string &filename);
        bool deleteFile(const std::string &filename);
        bool fileExists(const std::string &filename);

        // 目录管理
        void createDirectory(const std::string &dirname);
        bool directoryExists(const std::string &dirname);

    private:
        FileManager() = default;
        ~FileManager() = default;

        std::unordered_map<std::string, std::shared_ptr<FileHandle>> open_files_;
        const size_t BLOCK_SIZE = 4096; // 4KB块大小
    };

} // namespace MiniDB
